package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeMeum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 集中处理异常
 *
 * @author syf
 * @version 1.0
 * @see
 * @since
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.atguigu.gulimall.product")

@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product")
public class GulimallExceptionControllerAdvice {

     //精确匹配
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("处理数据校验异常", e.getMessage(), e.getClass(), e);
        HashMap<Object, Object> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().stream().forEach(en->{
                 //属性名称
                 String field = en.getField();
                 //错误信息
                 String defaultMessage = en.getDefaultMessage();
                 map.put(field, defaultMessage);
             });
        return  R.error(BizCodeMeum.VAILD_EXCEPTION.getCode(), BizCodeMeum.VAILD_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("处理全部异常", throwable.getMessage(), throwable.getClass(), throwable);
        return  R.error(BizCodeMeum.VAILD_EXCEPTION.getCode(), BizCodeMeum.VAILD_EXCEPTION.getMsg());
    }



}
